import React, { useMemo, useState } from "react";
import { Form, FormInstance, Select } from "antd";
import WidegetWrap from "./widgetWrap";
import Options from "./options";

const { Item: FormItem } = Form;

const RadioCfg = (props: ActivedElemnetType<RadioWidget>) => {
  const [options, setOptions] = useState<Array<FunOption> | undefined>(
    props.element.options
  );

  const hodleList = useMemo(
    () => options?.filter((x) => x.label && x.value) || [],
    [options]
  );
  return (
    <WidegetWrap {...props}>
      {(form: FormInstance) => {
        return (
          <>
            <FormItem noStyle name="options">
              <Options
                value={options}
                onChange={(value = []) => {
                  setOptions(value);
                  const defaultValue = form.getFieldValue("value");
                  if (
                    defaultValue &&
                    value.findIndex(({ value: v }) => v === defaultValue) > -1
                  ) {
                    form.setFieldsValue({ value: null });
                  }
                  form.setFieldsValue({
                    options: value,
                  });
                  form.submit();
                }}
              />
            </FormItem>
            <FormItem label="缺省" name="value">
              <Select
                placeholder="设置缺省值"
                allowClear
                onChange={(value) => {
                  form.setFieldsValue({ value: value });
                  form.submit();
                }}
              >
                {hodleList.map((opt, i) => (
                  <Select.Option key={opt.value + "_" + i} value={opt.value}>
                    {opt.label}
                  </Select.Option>
                ))}
              </Select>
            </FormItem>
          </>
        );
      }}
    </WidegetWrap>
  );
};

export default RadioCfg;
